package net.sf.nlp.segment.util;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;

public class Utility {

	/**
	 * 根据ID号得到对应的GB汉字
	 * 
	 * @param id
	 *          0--6767
	 * @return
	 */
	public static String getGB(int id) {
		String result = null;

		if (id >= 0 && id < 6768) {
			byte[] b = new byte[2];
			b[0] = (byte) ((id) / 94 + 176);
			b[1] = (byte) ((id) % 94 + 161);
			try {
				result = new String(b, "GBK");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	

	/**
	 * 汉字在6768区位表中对应的ID号
	 */
	public static int CC_ID(String str) 
	{
		int result = -1;
		if (str != null && str.length() > 0) {
			byte[] b;
			try {
				b = str.getBytes("GBK");
			} catch (UnsupportedEncodingException e) {
				b = str.getBytes();
				e.printStackTrace();
			}
			result = (getUnsigned(b[0]) - 176) * 94 + (getUnsigned(b[1]) - 161);
		}
		return result;
	}
	
	public static int getUnsigned(byte b) 
	{
		if (b > 0)
			return (int) b;
		else
			return (b & 0x7F + 128);
	}
	
	public static long getLong(InputStream is) throws Exception
	{
		long val = 0;
		byte[] b = new byte[4];
		
		is.read(b);
		
		for (int i = 0, j = 0; i < b.length - 1; i++, j++) 
		{
			long temp = (long) (b[i] & 0xFF);
			val += temp << (j <<3);
		}
		
		return val;
	}
	
	public static String getString(InputStream is, int length) throws Exception
	{
		if (length == 0)
			return null;
		
		byte[] b = new byte[length];
		
		is.read(b);
		
		return new String(b, "GBK");
	}
	
	public static int binarySearch(int val, int[] table) 
	{
		if (table != null) 
		{
			int len = table.length;
			int start = 0, end = len - 1, mid = (start + end) / 2;

			while (start <= end)// Binary search
			{
				if (table[mid] == val) {
					return mid;// find it
				} else if (table[mid] < val) {
					start = mid + 1;
				} else {
					end = mid - 1;
				}
				mid = (start + end) / 2;
			}
		}
		return -1;// Can not find it;
	}
}
